package com.sansi.bleFloodlight.activity;

import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.a1anwang.okble.client.scan.BLEScanResult;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.blelibrary.ble.BleCommand;

import com.my.httpapi.api.annotation.Layout;
import com.my.httpapi.api.baseView.BaseActivity;
import com.sansi.bleFloodlight.R;
import com.sansi.bleFloodlight.ble.BleManageUtils;
import com.sansi.bleFloodlight.ble.bleInterface.BleManageListener;
import com.sansi.bleFloodlight.ble.bleInterface.IBleManage;
import com.sansi.bleFloodlight.db.TableDevice;
import com.sansi.bleFloodlight.model.RemoveLightEvent;
import com.sansi.bleFloodlight.utils.ActivityUtils;
import com.sansi.bleFloodlight.utils.RouterPath;
import com.sansi.bleFloodlight.view.CustomDialog;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.util.List;


@Layout(R.layout.layout_activity_device_setting)
@Route(path = RouterPath.deviceInfoPath)
public class DeviceSettingActivity extends BaseActivity implements BleManageListener {
    private LinearLayout llFirmwareUpdate;
    private TextView tvDisconnect;
    private IBleManage iBleManage;

    @Autowired
    public BluetoothDevice device;

    private int int_write = -1;// 0-写入netkey  1-删除设备
    private HandlerThread handlerThread;
    private Handler workHandler;
    public static final int INT_UNIND = 3;
    public static final int SEND_UNBIND = 4;

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        llFirmwareUpdate = findViewById(R.id.ll_firmware_update);
        tvDisconnect = findViewById(R.id.tv_disconnect);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        BLEScanResult bleScanResult = new BLEScanResult(device, new byte[0], 0);
        iBleManage = new BleManageUtils(this, this);
        iBleManage.setBLEScanResult(bleScanResult);
        iBleManage.connect(false);

        llFirmwareUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RouterPath.gotoFirmwareUpdatePath();
            }
        });
        tvDisconnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog();
            }
        });

        handlerThread = new HandlerThread("unbindDevice");
        handlerThread.start();
        workHandler = new Handler(handlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case INT_UNIND:
                        int_write = 0;
                        iBleManage.writeData(BleCommand.getNetkeyData(ActivityUtils.getLocalNetKey(), 16));
                        break;
                    case SEND_UNBIND:
                        int_write = 1;
                        List<TableDevice> listDevice = LitePal.findAll(TableDevice.class);
                        for (int i = 0; i < listDevice.size(); i++) {
                            TableDevice tableDevice = listDevice.get(i);
                            if (tableDevice.getMac().equals(device.getAddress())) {
                                byte[] data = BleCommand.getDeleteDeviceData(ActivityUtils.toBytes(tableDevice.getUnicast_address()), 2);
                                iBleManage.writeData(data);
                                break;
                            }
                        }
                        break;
                }
            }
        };
    }

    @Override
    protected void destory() {
        if (handlerThread != null)
            handlerThread.quit();
    }

    @Override
    protected String showTitle() {
        return "light information";
    }

    @Override
    protected boolean statusBarIsBlack() {
        return false;
    }

    @Override
    protected boolean showLeftArrow() {
        return true;
    }

    private void showDialog() {
        new CustomDialog.Builder(this)
                .setTitle("Do you want to remove the connection?")
                .setPositiveButton("REMOVE", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        message_init_bind();
                    }
                }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {


            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).create().show();
    }

    @Override
    public void openNotify() {

    }

    @Override
    public void onDisconnected() {

    }

    @Override
    public void onReceivedValue(String uuid, int code,String value) {
        if (int_write == 0 && code==BleManageUtils.SUCESS) {
            message_send_bind();
        } else if (int_write == 1 && code==BleManageUtils.SUCESS) {
            finish();
            EventBus.getDefault().post(new RemoveLightEvent(device.getAddress()));
        }
    }

    private void message_init_bind() {
        Message msg = Message.obtain();
        msg.what = INT_UNIND;
        workHandler.sendMessage(msg);
    }

    private void message_send_bind() {
        Message msg = Message.obtain();
        msg.what = SEND_UNBIND;
        workHandler.sendMessage(msg);
    }
}
